<template>
  <el-select
    style="width: 100%"
    v-model="comValue"
    :multiple="multiple"
    collapse-tags
    collapse-tags-tooltip
    placeholder="请选择"
    :disabled="disabled"
    :clearable="clearable"
    :filterable="filterable"
  >
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="item.name"
      :value="item.id"
    />
  </el-select>
</template>
<script setup>
// import { getYLOrgOptions } from '@/api/api'
import {get_api_module} from '@/api/system'
import { useUserStore } from '@/pinia/modules/user'
const changeTitle = inject("changeTitle",()=>{})
const emit = defineEmits(['update:modelValue', 'change'])
const props = defineProps({
  filterable: {
    type: Boolean,
    default: false
  },
  modelValue: {
    type: String,
    default: ''
  },
  type: {
    type: [String, Number],
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false
  },
  multiple: {
    type: Boolean,
    default: false
  },
  clearable: {
    type: Boolean,
    default: false
  },
  url:{
    type:String,
    default:''
  },
  firstValue: {
    type: Boolean,
    default: false
  },
  params: {
    type: Object,
    default: {}
  },
  watchKey:{
    type:String,
    default:''
  },
  watchValue:{
    type:[String,Number],
    default:''
  }
})
const options = ref([])
const comValue = computed({
  get() {
    if (props.multiple) {
      return props.modelValue ? props.modelValue.split(',') : []
    }
    return props.modelValue
  },
  set(val) {
    if (props.multiple) {
      emit('update:modelValue', val.join())
    } else {
      emit('update:modelValue', val)
      let target = options.value.filter(item => item.id == val)[0]
      emit('change', target)
      changeTitle(target)
    }
  }
})
const orgInfo = useUserStore().orgInfo
const allUrl = {
  get_api_module
}
watch(() => props.watchValue, async (val) => {
  if(val){
    await getOptions()
    emit('update:modelValue', '')
  }
})
const getOptions = async ()=>{
  const res = await allUrl[props.url]({...props.params,[props.watchKey]:props.watchValue})
  if (res.data && res.data.length > 0) {
    let arr = []
    res.data.forEach((item, index) => {
      arr.push({
        name: item.name,
        id: item.code
      })
    })
    options.value = arr
  } else {
    options.value = []
  }
}
onMounted(() => {
  // getOptions()
})
</script>
<style lang="scss" scoped></style>
